<template>
  <div>
    <div class="tenantry-manage">
      <div class="card-box">
        <div class="card-title">基本信息</div>
        <el-form ref="propForm" :model="propForm" class="form-wrap" size="small" :rules="rules">
          <el-form-item label="供应商名称" class="col-one" prop="clientProviderName">
            <el-input maxlength="24" v-model="propForm.clientProviderName" placeholder="请输入供应商名称，最长为24位,不可为空"></el-input>
          </el-form-item>
          <el-form-item label="供应商类型" class="col-two" prop="clientProviderType">
            <el-select
              v-model="propForm.clientProviderType"
              value-key="label"
              @change="queryCertificateType"
              @blur="initType"
              filterable
              :filter-method="provideDataFilter"
            >
              <el-option v-for="item in providerOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <!-- 第一行第3列-->
          <el-form-item label="证件类型" class="col-three" prop="certificateType">
            <el-select v-model="propForm.certificateType" value-key="label" filterable :filter-method="certificateDataFilter" @blur="initNum">
              <el-option v-for="item in certificateOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <!-- 第一行第4列  :证件号码列-->
          <el-form-item label="证件号码" class="col-four" prop="certificateNum">
            <el-input v-bind:disabled="!propForm.certificateType" v-model="propForm.certificateNum" maxlength="24" placeholder="请先选择供应商类型，再选择证件类型，才能填写证件号码"></el-input>
          </el-form-item>

          <!-- 第二行第1列-->
          <el-form-item label="供应商负责人" class="col-one" prop="providerPrincipal">
            <el-input v-model="propForm.providerPrincipal" maxlength="24" placeholder="请输入供应商负责人(最长为24位)，可为空"></el-input>
          </el-form-item>
          <!-- 第二行第2列-->
          <el-form-item label="联系电话" class="col-two" prop="phoneNum">
            <el-input v-model="propForm.phoneNum" oninput="if(value.length>11)value=value.slice(0,11)" maxlength="11" placeholder="请输入11位数字的联系电话,不可为空"></el-input>
          </el-form-item>
          <!-- 第二行第3列-->
          <el-form-item label="电子邮箱" class="col-three" prop="email">
            <el-input v-model="propForm.email" maxlength="32" placeholder="请输入电子邮箱,不可为空"></el-input>
          </el-form-item>
          <!-- 第二行第4列 :都一样-->
          <el-form-item label="固定电话" class="col-four" prop="telephone">
            <el-input v-model="propForm.telephone" oninput="value=value.replace(/[^0-9-]+/,'')" maxlength="16" placeholder="请输入固定电话,不可为空"></el-input>
          </el-form-item>

          <el-form-item label="业务范围" class="col-one" prop="scopeBusiness">
            <el-input v-model="propForm.scopeBusiness" maxlength="18" placeholder="请输入业务范围,最长为18位，可为空"></el-input>
          </el-form-item>
          <el-form-item label="通讯地址" prop="address" class="col-two">
            <el-input v-model="propForm.address" maxlength="100" placeholder="请输入详细地址"></el-input>
          </el-form-item>
          <el-form-item label="引进单位" class="col-three" prop="introduceUnit">
            <el-input v-model="propForm.introduceUnit" maxlength="36" placeholder="请输入引进单位，可为空"></el-input>
          </el-form-item>
          <el-form-item label="备注" class="full" prop="remarks">
            <el-input v-model="propForm.remarks" maxlength="100" placeholder="请输入备注(长度最长为100)，可为空"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 如果是新增时，可以切换类型
                          :editPersons="editPersons"
    :delPersons="delPersons"-->
    <div class="tenantry-manage">
      <providerPersonInfo ref="privoderPersonInfo" :pid="propForm.supplierId" :isAdd="isAdd"></providerPersonInfo>
    </div>

    <div class="tenantry-manage">
      <div class="card-box">
        <div class="card-title">文件上传</div>
        <div style="padding:20px 20px 0;">
          <v-upload type="file" ref="upload" :busId="propForm.supplierId" modelType="supplierManage" @onSuccess="onSuccess" v-model="uploadFileList" />
        </div>
      </div>
    </div>
    <div class="tenantry-manage">
      <div class="card-box">
        <el-form size="small" class="but_form">
          <el-form-item class="col-two">
            <el-button type="primary" v-throttle="[submit]">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import personInfo from '@/views/client-manage/components/person-info.vue'
import providerPersonInfo from '@/views/client-manage/components/provider-person-info.vue'
import uploadMedia from '@/components/upload-media.vue'
import { getObj, addObj, putObj, cardCheck } from '@/views/client-manage/api/clientprovider'
import { validatePhoneTwo } from '~/utils/validate'
import { getDictAndPlease } from "~/utils"
export default {
  components: {
    personInfo,
    uploadMedia,
    providerPersonInfo
  },
  beforeMount () {
    if (this.$route.query.id) {
      this.isAdd = false
      this.propForm.supplierId = this.$route.query.id
      this.init()
    }
    // 获取出租方类型
    this.initProvicerType();
    this.queryCertificateType();
  },
  data () {
    const checkPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入联系方式'))
      } else {
        const reg = /^(1[123456789]\d{9})$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的电话'))
        }
      }
    }

    const checkEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电子邮箱'))
      } else {
        const reg = /^\w+@[a-z0-9]+\.[a-z]{2,4}$/;
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的邮箱'))
        }
      }
    }
    return {
      // 表单数据
      propForm: {
        supplierId: '',
        clientProviderName: '',
        clientProviderType: '',
        certificateType: '',
        certificateNum: '',
        providerPrincipal: '',
        phoneNum: '',
        email: '',
        telephone: '',
        scopeBusiness: '',
        areaCode: '',
        address: '',
        introduceUnit: '',
      },
      // 供应商类型列表
      providerOptions: [],
      providerOptionsCopy: [],
      /*     lesseeOptions:[],
           lesseeOptionsCopy:[],*/
      certificateOptions: [],
      certificateOptionsCopy: [],
      // 上传文件列表
      uploadFileList: [],
      // 是否是新增场景
      isAdd: true,
      // 表单校验
      rules: {
        clientProviderName: [{ required: true, message: '供应商名称不能为空', trigger: 'blur' },
        { min: 0, max: 24, message: "长度在0-24个字符串", trigger: "blur" },],
        remarks: [
        ],
        clientProviderType: [{ required: true, message: '供应商类型不能为空', trigger: 'blur' }
        ],
        certificateType: [{ required: true, message: '证件类型不能为空', trigger: 'blur' }
        ],
        providerPrincipal: [
        ],
        phoneNum: [{ required: true, message: '联系电话不能为空', trigger: 'blur' },
        { validator: checkPhone, trigger: "blur" },
        ],
        email: [{ required: true, message: '电子邮箱不能为空', trigger: 'blur' },
        { validator: checkEmail, trigger: "blur" },
        ],
        telephone: [{
          required: true,
          message: "请输入正确的电话号码或者固话号码(0754-XXXXXXXX)",
          trigger: ['blur']
        },
        {
          validator: validatePhoneTwo,
          trigger: "blur"
        },
        {
          pattern: /^((0\d{2,3}-\d{7,8})|(1[23456789]\d{9}))$/,
          message: '请输入正确的电话号码或者固话号码(0754-XXXXXXXX)'
        },
        ],
        scopeBusiness: [
        ],
        addressInfo: [
        ],
        address: [
        ],
        introduceUnit: [],
        certificateNum: [{ required: true, message: "请输入证件号码", trigger: "blur" },
        { validator: this.validCertificateNum, trigger: 'blur' },
        ],

      },
    }
  },
  methods: {
    validCertificateNum (rule, value, callback) {
      if (this.propForm.certificateType == 0) {
        /* let Ancode;//营业执照代码的每一个值
         let Ancodevalue;//营业执照代码每一个值的权重
         let total = 0;
         let weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];//加权因子
         //不用I、O、S、V、Z
         let str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
         for (let i = 0; i < value.length - 1; i++) {
             Ancode = value.substring(i, i + 1);
             Ancodevalue = str.indexOf(Ancode);
             total = total + Ancodevalue * weightedfactors[i];
             //权重与加权因子相乘之和
         }
         let logiccheckcode = 31 - total % 31;
         if (logiccheckcode == 31) {
             logiccheckcode = 0;
         }
         let Str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";
         let Array_Str = Str.split(',');
         logiccheckcode = Array_Str[logiccheckcode];
         let checkcode = value.substring(17, 18);
         if (logiccheckcode != checkcode) {
             callback(new Error('校验失败，请输入正确的18位营业执照！'));
         }*/
        if (!/^(?!^[A-Z]+$)[A-Z0-9]{8,18}$/.test(value)) {
          return callback(new Error('请输入由大写字母、数字组成或纯数字的8到18位营业执照代码 ！'));
        }
      }
      //税务登记号
      if (this.propForm.certificateType == 3) {
        var reg = /^(?!^[A-Z]+$)[A-Z0-9]{15}$|^(?!^[A-Z]+$)[A-Z0-9]{17}$|^(?!^[A-Z]+$)[A-Z0-9]{18}$|^(?!^[A-Z]+$)[A-Z0-9]{20}$/;
        if (!reg.test(value)) {
          return callback(new Error('请输入由大写字母、数字组成或纯数字的15或者17或者18或者20位税务登记号 ！'));
        }
      }
      //统一社会信用代码
      if (this.propForm.certificateType == 2) {
        /*let Ancode;//统一社会信用代码的每一个值
        let Ancodevalue;//统一社会信用代码每一个值的权重
        let total = 0;
        let weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];//加权因子
        //不用I、O、S、V、Z
        let str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
        for (let i = 0; i < value.length - 1; i++) {
            Ancode = value.substring(i, i + 1);
            Ancodevalue = str.indexOf(Ancode);
            total = total + Ancodevalue * weightedfactors[i];
            //权重与加权因子相乘之和
        }
        let logiccheckcode = 31 - total % 31;
        if (logiccheckcode == 31) {
            logiccheckcode = 0;
        }
        let Str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";
        let Array_Str = Str.split(',');
        logiccheckcode = Array_Str[logiccheckcode];
        let checkcode = value.substring(17, 18);
        if (logiccheckcode != checkcode) {
            callback(new Error('校验失败，请输入正确的18位统一社会信用代码！'));
        }*/
        if (!/^(?!^[A-Z]+$)[A-Z0-9]{8,18}$/.test(value)) {
          return callback(new Error('请输入由大写字母、数字组成或纯数字的8到18位统一社会信用码 ！'));
        }
      }
      //组织机构代码
      if (this.propForm.certificateType == 1) {
        /*if (value === "") {
            callback(new Error("请输入组织机构代码"));
        } else if (value.length != 9) {
            callback(new Error("组织机构代码位数不正确"));
        } else {
            // var patrn = /^[0-9A-Z]+$/;
            var reg = /^[0-9A-Z]+$/;
            if (reg.test(value) == false) {
                callback(new Error("组织机构代码只可为数字或大写拉丁字母"));
            } else {
                var regLast = /^[0-9X]+$/;

                var lastnum = value.substring(8, 9);

                if (regLast.test(lastnum) == false) {
                    callback(
                        new Error("组织机构代码最后一位只可为数字或大写拉丁字母 X")
                    );
                } else {
                    var ancode;
                    var ancodeWeightValue;
                    var sum = 0;
                    var weightedArray = [3, 7, 9, 10, 5, 8, 4, 2]; //加权因子
                    var str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    for (var i = 0; i < value.length - 1; i++) {
                        ancode = value.substring(i, i + 1);
                        ancodeWeightValue = str.indexOf(ancode);
                        sum = sum + ancodeWeightValue * weightedArray[i];
                    }
                    var rightLastnum = 11 - (sum % 11);
                    if (rightLastnum == 10) rightLastnum = "X";
                    if (rightLastnum == 11) rightLastnum = "0";
                    if (lastnum != rightLastnum) {
                        callback(new Error("组织机构代码结构错误！"));
                    }
                }
            }
        }*/

        if (!/^(?!^[A-Z]+$)[A-Z0-9]{8,18}$/.test(value)) {
          return callback(new Error('请输入由大写字母、数字组成或纯数字的8到18位组织机构代码 ！'));
        }
      }

      let certificateType = this.propForm.certificateType;
      let clientLesseeType = this.propForm.clientLesseeType
      if (!this.originalCertificateNum === this.propForm.certificateNum) {
        cardCheck({ "clientLesseeType": clientLesseeType, "certificateType": certificateType, "certificateNum": value }).then(respdata => {
          var item = respdata.data.data
          if (item.length > 0) {
            return callback(new Error('校验失败，该证件号码已经存在 ！'));
          } else {
            return callback()
          }
        })
      } else {
        return callback()
      }

    },
    initType () {
      this.propForm.certificateType = '',
        this.initNum()

    },
    initNum () {
      this.propForm.certificateNum = ''
    },
    // 初始化
    async init () {
      const res = await getObj(this.propForm.supplierId);
      if (res.data.code == 0) {
        let data = res.data.data;
        this.propForm.certificateType
        this.propForm = data
        data.clientProviderType && this.queryCertificateType()
      } else {
        this.$message.error(res.data.msg)
      }
    },
    //初始化承租方类型
    initProvicerType () {
      this.providerOptions = getDictAndPlease('provider_type')
      this.providerOptionsCopy = this.providerOptions
    },
    //点击承租方类型下拉列表后，查询对应的证件类型
    queryCertificateType () {
      this.certificateOptions = getDictAndPlease('commercial_certificate_type')
      this.certificateOptionsCopy = this.certificateOptions
    },
    // 表单提交
    async submit () {


      var form = this.$refs['privoderPersonInfo'];
      try {
        var a = await this.$refs.propForm.validate()
        var c = await form.$refs.form.validate()
        if (a && c) {
          this.uploadFileList.length > 0 ? this.$refs.upload.submit('supplierManage', this.propForm.supplierId) : this.submitForm()
        } else {
          return false;
        }
      } catch (e) {
        return false;
      }
      /*    this.$refs.propForm.validate(valid => {
              if(valid && this.$refs['privoderPersonInfo'].formVerify ) {
                  this.uploadFileList.length > 0 ? this.$refs.upload.submit('supplierManage', this.propForm.supplierId) : this.submitForm()
                  console.log('supplierId',this.propForm)
              }else{
                  return false;
              }
          })*/
    },
    // 文件上传成功
    onSuccess (response, file, fileList) {
      if (response.data) {
        this.submitForm(this.$refs.upload.loadFileList.length > 0 ? '' : response.data)
        //this.$refs.loadFiles.getFiles(response.data);
      } else {
        this.err('提交失败')
      }
    },
    // 表单保存
    submitForm (val = '') {
      let supplierId = this.isAdd ? val : this.propForm.supplierId;
      let ref = this.$refs['privoderPersonInfo'];
      //联系人列表
      let clientProviderLinkinfos = ref.form.editPersons.map(item => ({ ...item, supplierId }))
      // 接口参数
      let requestData = { ...this.propForm, supplierId, clientProviderLinkinfos }
      // 新增
      if (this.isAdd) {
        addObj(requestData).then(res => {
          this.$store.commit("delHistoryRoute", this.$route.fullPath);
          if (res.data.code == 0) {
            this.$message.success(this.isAdd ? '添加成功' : '修改成功')
            this.$router.back()
          } else {
            this.$message.error(this.isAdd ? '添加失败' : '修改失败');
          }
          // res.data.code == 0 ? this.$router.back() : this.$message.error(this.isAdd ? '新增失败' : '修改失败');
        })
      } else {
        putObj(requestData).then(res => {
          this.$store.commit("delHistoryRoute", this.$route.fullPath);
          if (res.data.code == 0) {
            this.$message.success(this.isAdd ? '添加成功' : '修改成功')
            this.$router.back()
          } else {
            this.$message.error(this.isAdd ? '添加失败' : '修改失败');
          }
          // res.data.code == 0 ? this.$router.back() : this.$message.error(this.isAdd ? '新增失败' : '修改失败');
        })
      }

    },
    provideDataFilter (val) {
      this.formData.clientProviderType = val;
      if (val) { //val存在
        this.providerOptions = this.providerOptionsCopy.filter((item) => {
          if (!!~item.label.indexOf(val) || !!~item.label.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          }
        })
      } else { //val为空时，还原数组
        this.providerOptions = this.providerOptionsCopy;
      }
    },
    certificateDataFilter (val) {
      this.formData.certificateType = val;
      if (val) { //val存在
        this.certificateOptions = this.certificateOptionsCopy.filter((item) => {
          if (!!~item.label.indexOf(val) || !!~item.label.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          }
        })
      } else { //val为空时，还原数组
        this.certificateOptions = this.certificateOptionsCopy;
      }
    },

    //验证证件号唯一
    validateCertificateNumOnly (value, callback) {
      let certificateType = this.propForm.certificateType;
      let clientProviderType = this.propForm.clientProviderType;
      if (certificateType === '01') {
        var reg = new RegExp('(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)')
        if (value === '' || value === undefined || value == null) {
          callback()
        } else {
          if ((!reg.test(value)) && value !== '') {
            callback(new Error('请输入正确的身份证号码'))
          }
        }
      } else if (certificateType === '02') {
        var reg = new RegExp('^[\u4E00-\u9FA5]{1,2}(字第)([0-9a-zA-Z]{4,8})(号?)$')
        if (value === '' || value === undefined || value == null) {
          callback()
        } else {
          if ((!reg.test(value)) && value !== '') {
            callback(new Error('请输入正确的军官证号码，如：军/兵/士/文/职/广/（其他中文） + "字第" + 4到8位字母或数字 + "号"'))
          }
        }
      } else if (certificateType === '03') {
        reg = new RegExp('^[HMhm]{1}([0-9]{10}|[0-9]{8})$')
        if (value === '' || value === undefined || value == null) {
          callback()
        } else {
          if ((!reg.test(value)) && value !== '') {
            callback(new Error('请输入正确的港澳台证号码，规则如下：H/M + 10位或8位数字'))
          }
        }
      } else if (certificateType === '04') {
        /*  reg = new RegExp('^([EeKkGgDdSsPpHh]\d{8}$)|(^(([Ee][a-fA-F])|([DdSsPp][Ee])|([Kk][Jj])|([Mm][Aa])|(1[45]))\d{7}$)')*/
        reg = new RegExp('^([a-zA-z]|[0-9]){9}$')
        if (value === '' || value === undefined || value == null) {
          callback()
        } else {
          if ((!reg.test(value)) && value !== '') {
            callback(new Error('请输入正确的护照号码,数字+字母，共9位'))
          }
        }
      } else if (certificateType === '05') {
        callback()
      }

      if (!this.originalCertificateNum === this.propForm.certificateNum) {
        cardCheck({ "clientProviderType": clientProviderType, "certificateType": certificateType, "certificateNum": value }).then(resp => {
          let data = resp.data
          if (data.length != 0) {
            return callback(new Error("校验失败，该证件号码已经存在 ！"));
          } else {
            callback()
          }
        })
      } else {
        callback()
      }

    },
  }
}
</script>

<style scoped lang="scss">
@import "@/views/client-manage/scss/edit";
</style>
